﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using Model;

namespace BehaviorModel
{
    /// <summary>
    /// Entity which accumulates free Requests and gives you access to them.
    /// To get instance of RequestPool use getInstance() method.
    /// </summary>
    public sealed class RequestPool : IRequestPool
    {
        private readonly LinkedList<Request> _freeRequests = new LinkedList<Request>();

        private static readonly IRequestPool _instance = new RequestPool();

        private RequestPool() { }

        /// <summary>
        /// Use it to get RequestPool
        /// </summary>
        /// <returns>Instance of RequestPool</returns>
        public static IRequestPool GetInstance()
        {
            return _instance;
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public Request GetFreeRequest()
        {
            //if (0 == _freeRequests.Count)
            {
                return new Request();
            }

            var request = _freeRequests.First();
            _freeRequests.RemoveFirst();
            return request;
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public void ReturnRequest(Request request)
        {
            //CleanRequest(request);
            //_freeRequests.AddLast(request);
        }

        /// <summary>
        /// Method makes request free
        /// </summary>
        /// <param name="request">request which is gonna be made free</param>
        private void CleanRequest(Request request)
        {
            request.Id = Guid.NewGuid();
            request.InitTime = 0;
            request.CommonServiceTime = 0;
            request.CommonWaitingTime = 0;
            request.LastQueueWaitingTime = 0;
        }
    }
}
